/*******************************************************
 *Copyright (c) 2017 All Rights Reserved.
 *JDK版本： 1.8
 *公司名称：
 *命名空间：com.caltco.cargo.ops.service.impl
 *文件名：  SysUserServiceImpl 
 *版本号：  V1.0.0.0
 *创建人：  daixirui
 *电子邮箱：daixirui@live.com
 *创建时间：2019-06-11 14:04
 *描述：
 *
 *=====================================================
 *修改标记
 *修改时间：2019-06-11 14:04
 *修改人：  daixirui
 *版本号：  V1.0.0.0
 *描述：
 *
 /******************************************************/
package com.caltco.cargo.ops.auth.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.caltco.cargo.ops.auth.bo.AdminUserDetails;
import com.caltco.cargo.ops.auth.entity.UserEntity;
import com.caltco.cargo.ops.auth.service.UserService;
import com.caltco.cargo.ops.auth.utils.JwtTokenUtil;
import com.caltco.cargo.ops.common.api.Result;
import com.caltco.cargo.ops.common.exception.RRException;
import com.caltco.cargo.ops.common.utils.PageUtils;
import com.caltco.cargo.ops.common.utils.RedisCacheUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${httpGet.url}")
    private String url;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Override
    public AdminUserDetails loadUserByUsernameRedis(String key) {
        // Redis验证token模式
        String loginKey = redisCacheUtil.getLoginKey(key);

        UserEntity sysUserEntity = JSON.parseObject(JSON.toJSONString(redisCacheUtil.hmget(loginKey)), UserEntity.class);

        String token = ObjectUtil.isNotNull(redisCacheUtil.hget(loginKey, "token")) ? redisCacheUtil.hget(loginKey, "token").toString() : null;

        if (sysUserEntity != null) {
            return new AdminUserDetails(sysUserEntity, token);
        }
        throw new RRException("Redis数据异常");
    }

    @Override
    public UserEntity getCurUserInfoByRedis(HttpServletRequest request) {
        String token = getToken(request);
        String username = null;
        // JWT解析用户信息
        Map<String, Object> user = jwtTokenUtil.getUserNameFromToken(token);
        // 判断用户名是否为空
        if (ObjectUtil.isNotNull(user.get("username"))) {
            username = user.get("username").toString();
        }
        // Redis验证token模式
        String loginKey = redisCacheUtil.getLoginKey(username);
        UserEntity userEntity = JSON.parseObject(JSON.toJSONString(redisCacheUtil.hmget(loginKey)), UserEntity.class);
        return userEntity;
    }

    @Override
    public String getToken(HttpServletRequest request) {
        String authToken = "";
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            // The part after "Bearer "
            // 获取JWT-Token
            authToken = authHeader.substring(tokenHead.length());
        }
        return authToken;
    }

    @Override
    public Long getUserId(HttpServletRequest request) {
        UserEntity curUserInfoByRedis = getCurUserInfoByRedis(request);
        return curUserInfoByRedis.getUserId();
    }

    @Override
    public PageUtils getUserListByPage(String authorization, JSONObject params) {
        String res = HttpRequest.post(url + "/api/system/user/getAccountListByPageInner")
                .header("Content-Type", "application/json")
                .header("Authorization", authorization)
                .body(String.valueOf(params))
                .execute().body();
        Result result = JSONUtil.toBean(res, Result.class);
        PageUtils pageUtils = JSONUtil.toBean((JSONObject) result.getResult(), PageUtils.class);
        log.info(res);
        return pageUtils;
    }

    @Override
    public List<UserEntity> getPersonalByUserIds(String authorization, JSONObject params) {
        String res = HttpRequest.post(url + "/api/system/user/getPersonalByUserIds")
                .header("Content-Type", "application/json")
                .header("Authorization", authorization)
                .body(String.valueOf(params))
                .execute().body();
        Result result = JSONUtil.toBean(res, Result.class);
        List<UserEntity> list = JSONUtil.toList((JSONArray) result.getResult(), UserEntity.class);
        log.info(res);
        return list;
    }

    @Override
    public UserEntity getUserInfoById(String authorization, JSONObject params) {

        String res = HttpRequest.post(url + "/api/system/user/getUserInfoByIdInner")
                .header("Content-Type", "application/json")
                .header("Authorization", authorization)
                .body(String.valueOf(params))
                .execute().body();
        Result result = JSONUtil.toBean(res, Result.class);
        UserEntity userEntity = JSONUtil.toBean((JSONObject) result.getResult(), UserEntity.class);
        return userEntity;
    }

    @Override
    public List<UserEntity> getUserInfoByRoleIds(String authorization, JSONObject params) {
        String res = HttpRequest.post(url + "/api/system/user/getUserInfoByRoleIds")
                .header("Content-Type", "application/json")
                .header("Authorization", authorization)
                .body(String.valueOf(params))
                .execute().body();
        Result result = JSONUtil.toBean(res, Result.class);
        List<UserEntity> list = JSONUtil.toList((JSONArray) result.getResult(), UserEntity.class);
        log.info(res);
        return list;
    }

}
